// 回车搜索
function onkey13(event) {
    if (event.keyCode == 13) {
        let keywords = $("#keywords").val();
        if(keywords == ""){
            return false;
        }
        searchBook();
        event.returnValue = false;
    }
}

// 获取提取码
function getExtCode(bookId) {
    $.get("/api/v1/search/get_ext_code?bookId=" + bookId,{"authorization":localStorage.think},function (data){
        let alibabaCloudExtCode = data.data.alibabaCloudExtCode;
        let baiduCloudExtCode = data.data.baiduCloudExtCode;
        $("#" + bookId).text("阿里云盘提取码：" + alibabaCloudExtCode + "，百度网盘提取码：" + baiduCloudExtCode);
        // 动态移除onlick方法，防止重复请求
        $("#" + bookId).removeAttr("onclick")
    })
}

// 首页搜索
function searchBook() {
    let keywords = $("#keywords").val();
    if(keywords == ""){
        return false;
    }
    keywords = encodeURIComponent(keywords);
    $.get("/api/v1/search/search_book?keywords=" + keywords + "&pageSize=10&pageNum=1",{"authorization":localStorage.think},function (data){
        $("#result").empty();
        $.each(data.list, function(n, value) {
            let result = "<div class='bookItem'><img src='" + value.avatar + "' alt=''><div class='bookInfo'><div class='bookName'>" + value.bookName + "</div><div class='otherInfo no-select'><a target='_blank' href='" + value.alibabaCloud + "'><img src='img/alibaba-cloud.png' alt=''></a></div><div class='otherInfo no-select'><a target='_blank' href='" + value.baiduCloud + "'><img src='img/baidu-cloud.png' alt=''></a></div><div class='otherInfo1'>编号：" + value.bookId + "</div><div id='" + value.bookId + "' class='otherInfo2 no-select' onclick='getExtCode(" + value.bookId + ")'>获取提取码</div></div><div class='bookAction'><a href=''><input type='button' onclick='preview(\"" + value.bookName + "\");return false' value='阅 读'></a></div></div>";
            $("#result").append(result);
        });

        // 等待结果返回以后，改变页面样式
        $("#search").css("top","15px");
        $("#search").css("left","20px");
        $("#search").css("height","44px");
        $("#search").css("width","1200px");
        $("#search").css("transform","translate(0%, 0%)");
        $("#logo").css("float","left");
        $("#logo").css("display","inline-block");
        $("#logo").css("width","176");
        $("#logo").css("height","44px");
        $("#logo").css("margin","0 20px 0 0");
        $("#result").css("display","block");
        // 去掉鼠标hover logo的小提示
        $("#tips-desc").css("display","none");
        $("#triangle").css("display","none");
        // 隐藏footer
        $("#footer").css("display","none");

        let page = "<div id='page' class='st_page'></div>";
            $("#result").append(page);
            $("#page").sPage({
                page: data.pageNum,//当前页码，必填
                total: data.total,//数据总条数，必填
                pageSize: 10,//每页显示多少条数据，默认10条
                showTotal: true,//是否显示总条数，默认关闭：false
                totalTxt: "共" + data.total + "条",//数据总条数文字描述，{total}为占位符，默认"共{total}条"
                noData: true,//没有数据时是否显示分页，默认false不显示，true显示第一页
                showSkip: false,//是否显示跳页，默认关闭：false
                showPN: true,//是否显示上下翻页，默认开启：true
                prevPage: "上一页",//上翻页文字描述，默认“上一页”
                nextPage: "下一页",//下翻页文字描述，默认“下一页”
                fastForward: 10,//快进快退页数，默认0表示不开启快进快退
                backFun: function(page) {
                    //点击分页按钮回调函数，返回当前页码
                    searchBook2(page,$("#keywords").val());
                }
            });
    });
}

// 分页搜索：结果列表页面二次搜索
function searchBook2(page,keywords) {
    var keywords = $("#keywords").val();
    if(keywords==""){
        return false;
    }
    keywords = encodeURIComponent(keywords);

    var p = page || 1;
    $.ajax({
        type: "GET",
        url: "/api/v1/search/search_book?keywords="+keywords +"&pageNum=" + p + "&pageSize=10",
        dataType: "json",
        data: {
            "authorization":localStorage.think
        },
        success: function(data) {
            $("#result").empty();
            $.each(data.list, function(n, value) {
                let result = "<div class='bookItem'><img src='" + value.avatar + "' alt=''><div class='bookInfo'><div class='bookName'>" + value.bookName + "</div><div class='otherInfo no-select'><a target='_blank' href='" + value.alibabaCloud + "'><img src='img/alibaba-cloud.png' alt=''></a></div><div class='otherInfo no-select'><a target='_blank' href='" + value.baiduCloud + "'><img src='img/baidu-cloud.png' alt=''></a></div><div class='otherInfo1'>编号：" + value.bookId + "</div><div id='" + value.bookId + "' class='otherInfo2 no-select' onclick='getExtCode(" + value.bookId + ")'>获取提取码</div></div><div class='bookAction'><a href=''><input type='button' onclick='preview(\"" + value.bookName + "\");return false' value='阅 读'></a></div></div>";
                $("#result").append(result);
            });

            var page = "<div id='page' class='st_page'></div>";
            $("#result").append(page);
            $("#page").sPage({
                page: data.pageNum,//当前页码，必填
                total: data.total,//数据总条数，必填
                pageSize: 10,//每页显示多少条数据，默认10条
                showTotal: true,//是否显示总条数，默认关闭：false
                totalTxt: "共" + data.total + "条",//数据总条数文字描述，{total}为占位符，默认"共{total}条"
                noData: true,//没有数据时是否显示分页，默认false不显示，true显示第一页
                showSkip: false,//是否显示跳页，默认关闭：false
                showPN: true,//是否显示上下翻页，默认开启：true
                prevPage: "上一页",//上翻页文字描述，默认“上一页”
                nextPage: "下一页",//下翻页文字描述，默认“下一页”
                fastForward: 10,//快进快退页数，默认0表示不开启快进快退
                backFun: function(page) {
                    //点击分页按钮回调函数，返回当前页码
                    searchBook2(page,$("#keywords").val());
                }
            });
        }
    })
}

// 预览PDF
function preview(bookName) {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    window.open('/js/pdfjs-2.9.359-dist/web/viewer.html?file=/api/v1/book/preview?filename%3D'+ encodeURI(encodeURIComponent(bookName)) +'.pdf','_blank');
}

// 双击首页logo弹出登录框样式
function login() {
    $("#login").css("position","absolute");
    $("#login").css("margin","-150px 0 0 -200px");
    $("#login").css("top","45%");
    $("#login").css("left","50%");
    $("#login").css("animation","showPanel 5s ease");
    $("#login").css("-moz-animation","showPanel 5s ease-in");
    $("#login").css("-webkit-animation","showPanel 0.5s ease");
    $("#login").css("width","400px");
    $("#login").css("height","300px");
    $("#login").css("background","white");
    $("#login").css("border-radius","10px");
    $("#login").css("opacity","1");
    $("#login").css("z-index","1");
    $("#login").css("display","block");
    $("#login").css("text-align","center");

    $("#login-logo").css("width","200px");
    $("#login-logo").css("margin","25px 0");

    // 遮罩
    $("#login-mask").css("position","absolute");
    $("#login-mask").css("display","block");
    $("#login-mask").css("top","0");
    $("#login-mask").css("left","0");
    $("#login-mask").css("width","100%");
    $("#login-mask").css("height","100%");
    $("#login-mask").css("background","#000");
    $("#login-mask").css("opacity","0.5");

    // mini_tips
    $("#mini_tips").text("");
}

// 登录框关闭按钮
function closeBtn() {
    $("#login").css("display","none");
    $("#login-mask").css("display","none");
}

// 注册成功框关闭按钮
function closeRegBtn() {
    $("#reg_success").css("display","none");
    $("#reg_success").css("display","none");
    $("#login-mask").css("display","none");
}

// 登录
function loginUser() {
    let email = $("#email").val();
    let password = $("#password").val();
    if (email == "" || password == "") {
        $("#mini_tips").text("账号或密码不能为空");
        $("#mini_tips").css("color","red");
        $("#mini_tips").css("font-size","12px");
        return false;
    }
    $.ajax({
        type: "POST",
        url: "/api/v1/user/login",
        data: {
            email: email,
            password: password
        },
        dataType: "json",
        success: function(data) {
            let token = data.data;
            if (token == "") {
                $("#mini_tips").text(data.msg);
                $("#mini_tips").css("color","red");
                $("#mini_tips").css("font-size","12px");
            }else {
                closeBtn();
                setToken(token);
            }
        }
    })
}

// 设置token
function setToken(token) {
    $("#login").css("display","none");
    $("#login-mask").css("display","none");
    // Check browser support
    if (typeof(Storage) !== "undefined") {
        localStorage.think = token;
        $("#logo").attr("src","/img/logo-on.png");
    }else {
        return false;
    }
}

// 注册成功，跳转登录
function regSuccessGoLogin() {
    $("#login-mask").css("display","none");
    $("#reg_success").css("display","none");
    login();
}


$(document).ready(function(){
    // 保持页面logo是已登录的logo状态
    if(localStorage.think != null)(
        $("#logo").attr("src","/img/logo-on.png")
    )

    // 账号激活以后跳转到首页，显示账号注册成功。
    let nowUrl = document.URL;
    let fromUrl = document.referrer;
    var reg = RegExp(/activation\?code=/);
    // 如果地址中包含激活标志并且localStorage.think登录空，没有登录过，弹出来显示
    if(reg.test(nowUrl) && localStorage.think == null) {
        $("#reg_success").css("position","absolute");
        $("#reg_success").css("margin","-150px 0 0 -200px");
        $("#reg_success").css("padding-top","60px");
        $("#reg_success").css("top","45%");
        $("#reg_success").css("left","50%");
        $("#reg_success").css("animation","showPanel 5s ease");
        $("#reg_success").css("-moz-animation","showPanel 5s ease-in");
        $("#reg_success").css("-webkit-animation","showPanel 0.5s ease");
        $("#reg_success").css("width","400px");
        $("#reg_success").css("height","240px");
        $("#reg_success").css("background","white");
        $("#reg_success").css("border-radius","10px");
        $("#reg_success").css("opacity","1");
        $("#reg_success").css("z-index","1");
        $("#reg_success").css("text-align","center");
        $("#reg_success").css("display","block");

        // 遮罩
        $("#login-mask").css("position","absolute");
        $("#login-mask").css("display","block");
        $("#login-mask").css("top","0");
        $("#login-mask").css("left","0");
        $("#login-mask").css("width","100%");
        $("#login-mask").css("height","100%");
        $("#login-mask").css("background","#000");
        $("#login-mask").css("opacity","0.5");
    }
});

